/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.adama.controller;

import fr.adama.dto.EmployeDTO;
import fr.adama.entite.Employe;
import fr.adama.service.EmployeService;
import java.util.List;
import java.util.Locale;
import javax.validation.Valid;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 *
 * @author mini-john
 */
@Controller
public class EmployeController {

    private static final Logger logger = LoggerFactory.getLogger(EmployeController.class);

    @Autowired
    private EmployeService employeService;

    @Autowired
    private MessageSource messageSource;

    @RequestMapping("/employe/index.do")
    public ModelAndView index() {
        return new ModelAndView("employe/index");
    }

    @RequestMapping(method = RequestMethod.GET, value = "/employe/add.do")
    public String addEmploye(ModelMap model) {

        EmployeDTO employe = new EmployeDTO();
        model.addAttribute("employe", employe);
        return "employe/add";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/employe/add.do")
    public ModelAndView insertEmploye(@Valid @ModelAttribute("employe") EmployeDTO employeDto, BindingResult result, RedirectAttributes redirectAttributes, Locale locale) {
        if (result.hasErrors()) {

            return new ModelAndView("employe/add", "employe", employeDto);
        }
        try {
            logger.info("Ajout de l'employe {} {}", employeDto.getNom(), employeDto.getPrenom());
            Long employeDtoId = employeService.add(employeDto, Employe.class);
            employeDto.setId(employeDtoId);
            redirectAttributes.addFlashAttribute("SUCCESS_MESSAGE", messageSource.getMessage("Employe.add.success", new String[]{""}, new Locale("fr")));
        } catch (DataIntegrityViolationException ex) {
            logger.error("Erreur d'ajout l'employe {}", employeDto.getNom(), ex);

            if (ex.getCause() instanceof ConstraintViolationException) {
                ConstraintViolationException cdts = (ConstraintViolationException) ex.getCause();
                if (cdts.getConstraintName().equalsIgnoreCase("NOMPRENOMEXISTEMPLOYE")) {
                    ObjectError error = new ObjectError("nom", messageSource.getMessage("Employe.add.error.adherent.exist", new String[]{employeDto.getNom(), employeDto.getPrenom()}, new Locale("fr")));
                    result.addError(error);
                    return new ModelAndView("employe/add", "employe", employeDto);
                }

            }
        }
        return new ModelAndView("redirect:/employe/show.do", "id", employeDto.getId());
    }

    @RequestMapping(method = RequestMethod.GET, value = "/employe/list.do")
    public ModelAndView listEmploye() {
        List<EmployeDTO> listEmploye = employeService.findAll(Employe.class, EmployeDTO.class);
        return new ModelAndView("employe/list", "listEmploye", listEmploye);

    }

    @RequestMapping(method = RequestMethod.GET, value = "/employe/show.do")
    public ModelAndView getEmployeById(@RequestParam(required = true, value = "id") Long id) {
        EmployeDTO employe = employeService.getById(id, Employe.class, EmployeDTO.class);

        return new ModelAndView("employe/show", "employe", employe);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/employe/update.do")
    public ModelAndView updateEmployeForm(@RequestParam(required = true, value = "id") Long id) {
        EmployeDTO employe = employeService.getById(id, Employe.class, EmployeDTO.class);

        return new ModelAndView("employe/update", "employe", employe);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/employe/update.do")
    public ModelAndView updateEmploye(@Valid @ModelAttribute("employe") EmployeDTO employeDto, BindingResult result, RedirectAttributes redirectAttributes, Locale locale) {
        if (result.hasErrors()) {

            return new ModelAndView("employe/update", "employe", employeDto);
        }
        try {
            logger.info("Mis à jour de l'employe {} {}", employeDto.getNom(), employeDto.getPrenom());
            employeService.update(employeDto, Employe.class);
            redirectAttributes.addFlashAttribute("SUCCESS_MESSAGE", messageSource.getMessage("Employe.update.success", new String[]{""}, new Locale("fr")));
        } catch (DataIntegrityViolationException ex) {
            logger.error("Erreur de mis a jour l'employe {}", employeDto.getNom(), ex);

            if (ex.getCause() instanceof ConstraintViolationException) {
                ConstraintViolationException cdts = (ConstraintViolationException) ex.getCause();
                if (cdts.getConstraintName().equalsIgnoreCase("nomPrenomExistEmploye")) {
                    ObjectError error = new ObjectError("nom", messageSource.getMessage("Employe.update.error.adherent.exist", new String[]{employeDto.getNom(), employeDto.getPrenom()}, new Locale("fr")));
                    result.addError(error);
                    return new ModelAndView("employe/update", "employe", employeDto);
                }

            }
        }
        return new ModelAndView("redirect:/employe/show.do", "id", employeDto.getId());
    }

    @RequestMapping(method = RequestMethod.GET, value = "/employe/search.do")
    public String searchPage(ModelMap model) {
        EmployeDTO employe = new EmployeDTO();
        model.addAttribute("employe", employe);
        return "employe/search";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/employe/search.do")
    public ModelAndView search(@ModelAttribute("employe") EmployeDTO employeDto) {
        List<EmployeDTO> listEmploye = employeService.searchByEntity(employeDto);
        return new ModelAndView("employe/search", "listEmploye", listEmploye);
    }

}
